package com.frank.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.frank.oss.service.OssService;
import com.frank.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 工具类获取值
        String endPoint = ConstantPropertiesUtils.END_POINT;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        InputStream inputStream = null;

        // 创建OSS实例
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        String filename;
        try {
            // 获取上传文件的输入流
            inputStream = file.getInputStream();
            // 获取文件名称
            filename = file.getOriginalFilename();
            // 对文件名进行处理：①防止重复覆盖问题：UUID；②分文件夹处理：2021/11/29/uuidstr_ludashi.jpg
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = String.format("%s/%s_%s", datePath, uuid, filename);
            // 调用OSS实例方法进行上传
            ossClient.putObject(bucketName, filename, inputStream);
            // 把上传文件路径返回
            //https://edu202111.oss-cn-beijing.aliyuncs.com/ludashi.jpg
            //https://edu202111.oss-cn-beijing.aliyuncs.com/2021/11/29/uuidstr_ludashi.jpg
            return String.format("https://%s.%s/%s", bucketName, endPoint, filename);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭OssClient
            ossClient.shutdown();
        }


    }
}
